<?php

namespace app\api\common;


use Exception;
use think\facade\Cache;

class Auth
{
    use Output;
    protected $key = 'abc!def@ghi#jklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()+~?/';

    /**
     * 验证签名
     * @param $data
     * @return false|string
     */
    public static function getSignkey($data){
        if(empty($data)){
            return false;
        }
        ksort($data); //按字典顺序排序
        $query = http_build_query($data);
        //aes加密
        return (new Auth)->encrypt($query);
    }

    /**
     * AES-128-ECB加密
     * @param $data
     * @return string
     */
    public function encrypt($data){

        $res = openssl_encrypt($data, 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA);
        return base64_encode($res);
    }

    /**
     * AEC-128-ECB解密
     * @param $data
     * @return false|string
     */
    public function decrypt($data){
        $res = base64_decode($data);
        $res = openssl_decrypt($res, 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA);
        return $res;
    }

    public static function getToken($time,$ip){
        $token = strtoupper(md5($time.'token'.$ip));
        return $token;
    }

    /**
     * 验证签名解密
     * @param $str
     * @return bool
     */
    public static function checkSignkey($str){
        //从缓存中取出签名
        $cacheData = Cache::get($str['token']);
        if(empty($cacheData)){
            throw new Exception('登录失效,请重新登陆');
        }
        //解密aes
        $data = (new Auth)->decrypt($cacheData);

        parse_str($data , $sign);//把查询字符串解析到变量中
        //验证设备号
        if(empty($sign['did']) || !isset($sign['did']) || $str['did'] != $sign['did']){
            throw new Exception('签名验证失败','10002');
        }

        //验证version
        if(empty($sign['version']) || !isset($sign['version'])  || $str['version'] != $sign['version']){
            throw new Exception('签名验证失败');
        }
        //验证 时间戳
        if(empty($sign['time']) || !isset($sign['time']) || $str['time'] != $sign['time']){
            throw new Exception('签名验证失败');
        }
        if(request()->ip() !== $sign['ip']){
            throw new Exception('已在其它设备登陆,请重新登陆');

        }

        //用户id为 $sign['auid'];
        return $sign;
    }

}
